package com.htdata.iiot.utils;

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.Random;

/**
 * 
 * @author 孙梦亚
 *
 */
public class ApiKey {
    private static final String PREFIX_TENANT = "t";
    private static final String PREFIX_DEVICE = "d";
    private static final String PREFIX_COMPONENT = "c";
    private static final String SPLITER = "_";
    private static final int MAX_LENGTH = 24;
    private static final String CHARSET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    /**
     * 为租户生成apikey
     * @param tenantId
     * @return
     */
    public static String genKeyForTenant(int tenantId) {
        return genKey(PREFIX_TENANT, String.valueOf(tenantId));
    }

    /**
     * 为设备生成apikey
     * @param deviceId
     * @return
     */
    public static String genKeyForDevice(int deviceId) {
        return genKey(PREFIX_DEVICE, String.valueOf(deviceId));
    }

    /**
     * 为组件生成apikey
     * @param serialNumber
     * @return
     */
    public static String genKeyForComponent(long serialNumber) {
        return genKey(PREFIX_COMPONENT, String.valueOf(serialNumber));
    }

    /**
     * 随机生成apikey
     * @param prefix
     * @param id
     * @return
     */
    private static String genKey(String prefix, String id) {
        StringBuilder builder = new StringBuilder();
        builder.append(prefix).append(SPLITER).append(id).append(SPLITER);
        int count = MAX_LENGTH - builder.length();
        Random rd = new Random();
        for (int i = 0; i < count; i++) {
            builder.append(CHARSET.charAt(rd.nextInt(CHARSET.length())));
        }
        try {
            return Base64.getEncoder().encodeToString(builder.toString().getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return builder.toString();
    }
}
